package com.zgkj.Zip.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	public static final String DATE_FORMAT_LONG = "yyyyMMddHHmmss";
	public static final String DATE_FORMAT_MEDIUM = "yyyyMMdd";
	public static final String DATE_FORMAT_SHORT = "HHmmss";
	public static final String DATE_FORMAT_MICRO = "yyyyMMddHHmmssSSS";
	/**
	 * 检查日期格式
	 *
	 * @param date
	 * @param dateFormat
	 * @return
	 */
	public static boolean isDateString(String date, String dateFormat) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		sdf.setLenient(false);
		if (date.length() != dateFormat.length()) {
			return false;
		}
		try {
			sdf.format(sdf.parse(date));
			return true;
		} catch (ParseException e) {
			return false;
		}

	}

	/**
	 * 将系统当前格式化日期 为 yyyy-MM-dd 的样式
	 *
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDate() {
		return formatDate(Calendar.getInstance().getTime(), "yyyy-MM-dd");
	}

	/**
	 * 将系统当前格式化日期 为 yyyyMMdd 的样式
	 *
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDateSimple() {
		return formatDate(Calendar.getInstance().getTime(), "yyyyMMdd");
	}
	/**
	 * 将系统当前格式化日期 为 yyyyMMddHHmmss 的样式
	 *
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDateTime() {
		return formatDate(Calendar.getInstance().getTime(), "yyyyMMddHHmmss");
	}
	/**
	 * 将系统当前格式化日期 为 yyyyMMdd的样式
	 * @return
	 */
	public static String getSystemDate() {
		return formatDate(Calendar.getInstance().getTime(), "yyyyMMdd");
	}
	/**
	 * 将系统当前格式化日期 为 MMdd的样式
	 * @return
	 */
	public static String getSystemDateMonth() {
		return formatDate(Calendar.getInstance().getTime(), "MMdd");
	}
	/**
	 * 将系统当前格式化日期 为 HHmmss的样式
	 * @return
	 */
	public static String getSystemTime() {
		return formatDate(Calendar.getInstance().getTime(), "HHmmss");
	}
	/**
	 * 将系统当前格式化日期 为 指定的样式
	 *
	 * @param pattern
	 *            yyyyMMddHHmmss
	 * @return
	 */
	public static String getSystemCurrentDate(String pattern) {
		return formatDate(Calendar.getInstance().getTime(), pattern);
	}

	/**
	 * 将系统当前格式化日期 为 yyyyMMddHHmmssSSS的样式
	 * @return
	 */
	public static String getSystemMicroTime() {
		return formatDate(Calendar.getInstance().getTime(), "yyyyMMddHHmmssSSS");
	}

	/**
	 * 将系统前一天格式化日期 为 yyyyMMdd 的样式
	 *
	 * @param date
	 * @return
	 */
	public static String getSystemBeforeDayDateSimple() {
		// 取得前一天的日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}

	public static String getBeforeMonthDateSimple(){
		//取得前一个月的日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1);
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}

	/**
	 * 将传入的日期转成制定格式的字串
	 *
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(Date date, String pattern) {
		if (date != null) {
			return new SimpleDateFormat(pattern).format(date);
		} else {
			return "";
		}
	}

	/**
	 * 将传入的日期转成制定格式的字串
	 *
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(String date, String oldPattern,
			String newPattern) {
		try {
			if (date != null) {
				Date d = new SimpleDateFormat(oldPattern).parse(date);
				return new SimpleDateFormat(newPattern).format(d);
			} else {
				return "";
			}
		} catch (ParseException e) {
			return "";
		}
	}

	/**
	 * 将当前系统日期转成制定格式的字串
	 *
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(String pattern) {
		return formatDate(Calendar.getInstance().getTime(), pattern);
	}

	/**
	 * 格式化时间 为 hh:mm:ss 的样式
	 *
	 * @param date
	 * @return
	 */
	public static String formatTime(Date date, String pattern) {

		if (date != null) {
			return new SimpleDateFormat(pattern).format(date);
		} else {
			return "";
		}
	}

	/**
	 * 计算 日期 calendar1 与 calendar2 之间的所查的天数 ,注：return calendar1 - calendar2
	 *
	 * @param calendar1
	 *            日期1
	 * @param calendar2
	 *            日期2
	 * @return 相差天数 = 日期1 - 日期2
	 */
	public static int dateSubtraction(Calendar calendar1, Calendar calendar2) {
		long daterange = calendar1.getTime().getTime()
				- calendar2.getTime().getTime();
		long time = 1000 * 3600 * 24;

		return (int) (daterange / time);
	}

	/**
	 * 计算 日期 date1 与 date2 之间的所相差的天数 ,
	 *
	 * @param date1
	 *            日期1
	 * @param date2
	 *            日期2
	 * @return 相差天数 = 日期1 - 日期2
	 */
	public static String dateSubtraction(Date date1, Date date2) {
		if (date1 == null || date2 == null) {
			return "";
		}

		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		return String.valueOf(dateSubtraction(calendar1, calendar2));

	}

	/**
	 * 计算 日期 dateStr1 与 dateStr2 之间的所相差的天数 ,
	 *
	 * @param date1
	 *            日期1
	 * @param date2
	 *            日期2
	 * @return 相差天数 = 日期1 - 日期2
	 * @throws Exception
	 */
	public static int yearSubtraction(String dateStr1, String dateStr2) throws Exception {
		if(dateStr1.length()!=8||dateStr2.length()!=8){
			throw new Exception("date error!!");
		}
		dateStr1 = dateStr1.substring(0,4)+"-"+dateStr1.substring(4,6)+"-"+dateStr1.substring(6);
		dateStr2 = dateStr2.substring(0,4)+"-"+dateStr2.substring(4,6)+"-"+dateStr2.substring(6);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(java.sql.Date.valueOf(dateStr1));
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(java.sql.Date.valueOf(dateStr2));
		Calendar calendar3 = Calendar.getInstance();
		if(calendar1.getTimeInMillis()<calendar2.getTimeInMillis()){
			calendar3 = calendar1;
			calendar1 = calendar2;
			calendar2 = calendar3;
		}
		int year = calendar1.get(Calendar.YEAR)-calendar2.get(Calendar.YEAR);
		calendar1.set(Calendar.YEAR, calendar2.get(Calendar.YEAR)); //换算为同一年
		if (calendar1.getTimeInMillis()>calendar2.getTimeInMillis()) {
			year++;
		}
		return year;
	}


	/**
	 * 将 yyyy/MM/dd 格式的日期字串，转成Calendar
	 *
	 * @param strDate
	 * @return
	 */
	public static Calendar transDate(String strDate) {
		if (strDate != null && strDate.length() >= 8) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(java.sql.Date.valueOf(strDate.replace('/', '-')));

			return calendar;
		} else {
			return null;
		}
	}

	/**
	 * 计算两个日期相差月数
	 *
	 * @param calendarDate1
	 * @param calendarDate2
	 * @return
	 */
	public static int computeMonth(Calendar calendarDate1,
			Calendar calendarDate2) {
		int iMonth = 0;
		int flag = 0;
		boolean isF = true;
		try {
			if (calendarDate2.equals(calendarDate1)) {
				return 0;
			}

			if (calendarDate1.after(calendarDate2)) {
				Calendar temp = calendarDate1;
				calendarDate1 = calendarDate2;
				calendarDate2 = temp;
				isF = false;
			}
			if (calendarDate2.get(Calendar.DAY_OF_MONTH) <= calendarDate1
					.get(Calendar.DAY_OF_MONTH)) {
				flag = 1;
			}

			if (calendarDate2.get(Calendar.YEAR) > calendarDate1
					.get(Calendar.YEAR)) {
				iMonth = ((calendarDate2.get(Calendar.YEAR) - calendarDate1
						.get(Calendar.YEAR))
						* 12 + calendarDate2.get(Calendar.MONTH) - flag)
						- calendarDate1.get(Calendar.MONTH)+1;
			} else {
				iMonth = calendarDate2.get(Calendar.MONTH)
						- calendarDate1.get(Calendar.MONTH) - flag+1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(isF){
			iMonth = 0-iMonth;
		}
		return iMonth;
	}

	/**
	 * 计算两个日期相差年数
	 *
	 * @param calendarDate1
	 * @param calendarDate2
	 * @return
	 * @throws ParseException
	 */
	public static int computeYear(String DateStr1,
			String DateStr2) throws ParseException {
		int iYear = 0;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        Calendar calendarDate1 = Calendar.getInstance();
        calendarDate1.setTime(sdf.parse(DateStr1));
        Calendar calendarDate2 = Calendar.getInstance();
        calendarDate2.setTime(sdf.parse(DateStr2));
		int iMonth = computeMonth(calendarDate1, calendarDate2);
		iYear = iMonth/12;
		int iYearY = iMonth%12;
		System.out.println(iYearY);
		if(iYearY>0){
			iYear = iYear+1;
		}
		return iYear;
	}
	/**
	 * 计算两个日期相差年数
	 *
	 * @param calendarDate1
	 * @param calendarDate2
	 * @return
	 */
	public static int computeYear(Calendar calendarDate1,
			Calendar calendarDate2) {
		int iYear = 0;

		int iMonth = computeMonth(calendarDate1, calendarDate2);
		iYear = iMonth/12;
		return iYear;
	}
	/**
	 * 计算两个日期相差月数
	 *
	 * @param dateStr1
	 * @param dateStr2
	 * @return
	 */
	public static int computeMonth(String dateStr1,
			String dateStr2)throws Exception {
		if((dateStr1.length()!=8) || (dateStr2.length()!=8)){
			throw new Exception("date error!!");
		}
		dateStr1 = dateStr1.substring(0,4)+"-"+dateStr1.substring(4,6)+"-"+dateStr1.substring(6);
		dateStr2 = dateStr2.substring(0,4)+"-"+dateStr2.substring(4,6)+"-"+dateStr2.substring(6);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(java.sql.Date.valueOf(dateStr1));
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(java.sql.Date.valueOf(dateStr2));
		return computeMonth(calendar1,calendar2);
	}



	/**
	 * 获取字符串日期的下一年的前一天.yyyyMMdd
	 * * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getNextY(String dateStr)
			throws ParseException {
		if(dateStr.length()!=8){
			return null;
		}
		dateStr = dateStr.substring(0,4)+"-"+dateStr.substring(4,6)+"-"+dateStr.substring(6);
		//System.out.println(dateStr);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(java.sql.Date.valueOf(dateStr));
		calendar.add(Calendar.YEAR, +1);
		calendar.add(Calendar.DATE, -1);
		//System.out.println(formatDate(calendar.getTime(), "yyyyMMdd"));
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}
	/**
	 * 获取字符串日期的n年的同一天.yyyyMMdd
	 * * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getNextYear(String dateStr,int yearNum)
			throws ParseException {
		if(dateStr.length()!=8){
			return null;
		}
		dateStr = dateStr.substring(0,4)+"-"+dateStr.substring(4,6)+"-"+dateStr.substring(6);
		//System.out.println(dateStr);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(java.sql.Date.valueOf(dateStr));
		calendar.add(Calendar.YEAR, yearNum);
		//System.out.println(formatDate(calendar.getTime(), "yyyyMMdd"));
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}

	/**
	 * 获取字符串日期d天后的n月的yyyyMMdd
	 * * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getNextDM(String dateStr,int d,int m)
			throws ParseException {
		if(dateStr.length()!=8){
			return null;
		}
		dateStr = dateStr.substring(0,4)+"-"+dateStr.substring(4,6)+"-"+dateStr.substring(6);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(java.sql.Date.valueOf(dateStr));
		calendar.add(Calendar.DATE, d);
		calendar.add(Calendar.MONTH, m);
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}

	/**
	 * 获取字符串日期n月d天后的yyyyMMdd
	 * * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getNextMD(String dateStr,int d,int m)
			throws ParseException {
		if(dateStr.length()!=8){
			return null;
		}
		dateStr = dateStr.substring(0,4)+"-"+dateStr.substring(4,6)+"-"+dateStr.substring(6);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(java.sql.Date.valueOf(dateStr));
		calendar.add(Calendar.MONTH, m);
		calendar.add(Calendar.DATE, d);
		return formatDate(calendar.getTime(), "yyyyMMdd");
	}


  /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
	 public static int daysBetween(String smdate,String bdate) throws ParseException{
	         SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
	         Calendar cal = Calendar.getInstance();
	         cal.setTime(sdf.parse(smdate));
	         long time1 = cal.getTimeInMillis();
	         cal.setTime(sdf.parse(bdate));
	         long time2 = cal.getTimeInMillis();
	         long between_days=(time2-time1)/(1000*3600*24);
		     return Integer.parseInt(String.valueOf(between_days));
	 }

	/**
	 * 将字符串日期转换成Date.
	 *
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDate(String date, String dateFormat)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		return sdf.parse(date);
	}

	/**
	 * 将字符串日期转换成Date.
	 *
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDate(String date)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.parse(date);
	}

	public static Date addDay(Date date, int interalDay) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DAY_OF_MONTH, 1);
		return c.getTime();
	}
	/**
	 * 获取季度数
	 * @param date
	 * @return
	 */
	 public static int getSeason(Date date) {
		int season = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int month = c.get(Calendar.MONTH);
		switch (month) {
		case Calendar.JANUARY:
		case Calendar.FEBRUARY:
		case Calendar.MARCH:
			season = 1;
			break;
		case Calendar.APRIL:
		case Calendar.MAY:
		case Calendar.JUNE:
			season = 2;
			break;
		case Calendar.JULY:
		case Calendar.AUGUST:
		case Calendar.SEPTEMBER:
			season = 3;
			break;
		case Calendar.OCTOBER:
		case Calendar.NOVEMBER:
		case Calendar.DECEMBER:
			season = 4;
			break;
		default:
			break;
		}
		return season;
	}
	    /**
	     * 取得季度最后一天
	     *
	     * @param date
	     * @return
	     */
	    public static Date getLastDateOfSeason(Date date) {
	         return getLastDateOfMonth(getSeasonDate(date)[2]);
	    }

	    /**
	     * 取得季度最后一天
	     *
	     * @param date
	     * @return
	     * @throws ParseException
	     */
	    public static String getLastDateOfSeason(String dateStr) throws ParseException {

	         return formatDate(getLastDateOfMonth(getSeasonDate(parseDate(dateStr))[2]),"yyyyMMdd");
	    }

	   /**
	     * 取得月最后一天
	     *
	     * @param date
	     * @return
	     */
	    public static Date getLastDateOfMonth(Date date) {
	        Calendar c = Calendar.getInstance();
	        c.setTime(date);
	        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
	        return c.getTime();
	    }

	    /**
	     * 取得季度月
	     *
	     * @param date
	     * @return
	     */
	    public static Date[] getSeasonDate(Date date) {
	        Date[] season = new Date[3];

	        Calendar c = Calendar.getInstance();
	        c.setTime(date);
	        int nSeason = getSeason(date);
	        if (nSeason == 1) {// 第一季度
	            c.set(Calendar.MONTH, Calendar.JANUARY);
	            season[0] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.FEBRUARY);
	            season[1] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.MARCH);
	            season[2] = c.getTime();
	        } else if (nSeason == 2) {// 第二季度
	            c.set(Calendar.MONTH, Calendar.APRIL);
	            season[0] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.MAY);
	            season[1] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.JUNE);
	            season[2] = c.getTime();
	        } else if (nSeason == 3) {// 第三季度
	            c.set(Calendar.MONTH, Calendar.JULY);
	            season[0] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.AUGUST);
	            season[1] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.SEPTEMBER);
	            season[2] = c.getTime();
	        } else if (nSeason == 4) {// 第四季度
	            c.set(Calendar.MONTH, Calendar.OCTOBER);
	            season[0] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.NOVEMBER);
	            season[1] = c.getTime();
	            c.set(Calendar.MONTH, Calendar.DECEMBER);
	            season[2] = c.getTime();
	        }
	        return season;
	    }
	public static void main(String[] args) throws Exception {
		String date1 = "20160930";
		String date2 = "20160529";
		System.out.println(computeMonth(date1,date2));
		System.out.println(computeYear(date1,date2));
	}
}
